package org.jeecg.modules.zhoupackage.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.jeecg.modules.degression.mapper.MlccPriceSystemPingleiMapper;
import org.jeecg.modules.degression.mapper.MyMlccDataTypeMapper;
import org.jeecg.modules.degression.mapper.MyMlccPriceSystemCostRecordMapper;
import org.jeecg.modules.degression.pojo.MlccDataType;
import org.jeecg.modules.degression.pojo.MlccPriceSystemCostRecord;
import org.jeecg.modules.degression.pojo.MlccPriceSystemPinglei;
import org.jeecg.modules.gwcjava.jiekou.entity.MlccUserInfo;
import org.jeecg.modules.zhouAdmin.admin.fabeicCenter.mapper.MySysUserMapper;
import org.jeecg.modules.zhouAdmin.admin.fabeicCenter.pojo.MySysUser;
import org.jeecg.modules.zhouAdmin.admin.orderCenterModule.mapper.MyMlccCompanyInfoMapper;
import org.jeecg.modules.zhouAdmin.admin.orderCenterModule.mapper.MyMlccPaidanOrderCostMapper;
import org.jeecg.modules.zhouAdmin.admin.orderCenterModule.pojo.MlccCompanyInfo;
import org.jeecg.modules.zhouAdmin.admin.util.SingleAndTeamOrderUtil;
import org.jeecg.modules.zhoupackage.mapper.*;
import org.jeecg.modules.zhoupackage.pojo.*;
import org.jeecg.modules.zhoupackage.pojo.myexcel.FuwujiaEntity;
import org.jeecg.modules.zhoupackage.service.IMySingleOrderService;
import org.jeecg.modules.zhoupackage.util.FabricUtil;
import org.jeecg.modules.zhoupackage.util.MyExcelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;

/**
 * 纽扣
 */
@SuppressWarnings("all")
@Service
public class MySingleOrderServiceImpl implements IMySingleOrderService {

    @Autowired
    MyMlccCategoryInfoMapper mapper;

    @Autowired
    MyMlccSingleOrderInfoMapper singleOrderInfoMapper;

    @Autowired
    FabricUtil fabricUtil;

    @Autowired
    CartMlccUserInfoMapper userInfoMapper;

    @Autowired
    MyBodySizeMapper bodySizeMapper;

    @Autowired
    MySizeInfoMapper sizeInfoMapper;

    @Autowired
    MyContrastColorMapper contrastColorMapper;

    @Autowired
    MyMlccOrderBodysizeMapper orderBodysizeMapper;

    @Autowired
    MyMlccReoairMapper reoairMapper;

    @Autowired
    MlccFabricInfoMapper fabricInfoMapper;

    @Autowired
    MyMlccEmbdtypePriceMapper embdtypePriceMapper;

    @Autowired
    MyMlccModuleSmallTemplateMapper moduleSmallTemplateMapper;

    @Autowired
    MyMlccCategoryInfoMapper categoryInfoMapper;

    @Autowired
    MyMlccButtonsInfoMapper buttonsInfoMapper;

    @Autowired
    MyMlccBusinessWaterInfoMapper waterInfoMapper;

    @Autowired
    MyTrackingOrderMapper trackingOrderMapper;

    @Autowired
    MyLocatiomMapper locatiomMapper;

    @Autowired
    MyMlccPriceSystemCostRecordMapper recordMapper;

    @Autowired
    MyMlccProductInfoMapper productInfoMapper;

    @Autowired
    MlccPriceSystemPingleiMapper priceSystemPingleiMapper;

    @Autowired
    MyMlccMutexInfoMapper mutexInfoMapper;

    @Autowired
    MlccGroupInfoMapper groupInfoMapper;

    @Autowired
    MyMlccMaterialLibuInfoMapper libuInfoMapper;

    @Autowired
    MyMlccDilinniInfoMapper dilinniInfoMapper;

    @Autowired
    SingleAndTeamOrderUtil singleUtil;

    @Autowired
    MyMlccPaidanOrderCostMapper paidanOrderCostMapper;

    @Autowired
    MySysUserMapper sysUserMapper;

    @Autowired
    MyMlccDataTypeMapper dataTypeMapper;

    @Autowired
    MyMlccCompanyInfoMapper companyInfoMapper;

    /**
     * 获取纽扣查询条件
     *
     * @param mouldId
     * @return
     */
    @Override
    public List<MlccCategoryInfo> getButtonSelect(int mouldId) {
        QueryWrapper<MlccCategoryInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", mouldId).eq("is_button", 1).eq("haschild", 1);
        return mapper.selectList(wrapper);
    }

    /**
     * 获取具体的纽扣列表
     *
     * @param buttonTypeId
     * @return
     */
    @Override
    public List<MlccButtonsInfo> getButtons(Integer buttonTypeId) {
        QueryWrapper<MlccButtonsInfo> wrapper = new QueryWrapper<>();
        if (buttonTypeId != null) {
            wrapper.eq("category_id", buttonTypeId);
        }
        return buttonsInfoMapper.selectList(wrapper);
    }

    /**
     * 获取当前用户个顶订单
     *
     * @param token
     * @return
     */
    @Override
    public List<MlccSingleOrderInfo> getSingleOrderList(String token, Date time, Integer status, String code) {
        if (!fabricUtil.checkToken(token)) return null;
        int userIDByToken = fabricUtil.getUserIDByToken(token);
        QueryWrapper<MlccSingleOrderInfo> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("user_id", userIDByToken).ne("status", 0);
        if (time != null) {
            wrapper1.ge("create_time", time);
        }
        if (status != null) {
            wrapper1.eq("status", status);
        }
        if (code != null) {
            wrapper1.eq("order_sn", code);
        }
        return singleOrderInfoMapper.selectList(wrapper1);
    }

    /**
     * 获取个订订单详情
     *
     * @param token
     * @param orderID
     * @return
     */
    @Override
    public MlccSingleOrderInfo getDingleOrderDetail(String token, String orderSn) {
        if (!fabricUtil.checkToken(token)) return null;
        return fabricUtil.getSingleOrderDetailById3(orderSn);
    }

    /**
     * 个订订单返修
     *
     * @param entity
     * @return
     */
    @Override
    public int addSingleOrderRepair(String token, MlccRepairOrderInfo entity) {
        if (!fabricUtil.checkToken(token)) return -1;
        MlccUserInfo userDetail = fabricUtil.getUserDetail(token);
        /*新建返修订单*/
        entity.setUserId(userDetail.getId() + "").setCreateBy(userDetail.getUsername()).setUpdateBy(userDetail.getUsername())
                .setType(0).setOrdertype(1);
        /*修改返修数据*/
        String[] bodySize = entity.getBodysizeValue().split(",");
        for (int i = 0; i < bodySize.length; i++) {
            String[] size = bodySize[i].split("/");
            MlccOrderBodysize bodysizeEntity = orderBodysizeMapper.selectById(size[0]);
            bodysizeEntity.setBodysizeValue(bodySize[1]);
            orderBodysizeMapper.updateById(bodysizeEntity);
        }
        return reoairMapper.insert(entity);
    }

    /**
     * 个订面料与辅料界面获取面料信息
     *
     * @param token
     * @param typeId
     * @param fabeicCode
     * @return
     */
    @Override
    public List<MlccFabricInfo> getSingleFabricList(String token, Integer typeId, String fabeicCode) {
        if (!fabricUtil.checkToken(token)) return null;
        QueryWrapper<MlccFabricInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 0);
        if (fabeicCode != null) {
            wrapper.like("fabric_code", fabeicCode);
        }
        if (typeId == 0) {
            wrapper.eq("is_mian_fu", 0);
        } else if (typeId == 1) {
            wrapper.eq("is_mian_fu", 1);
        } else if (typeId == 2) {
            wrapper.eq("is_mian_fu", 2);
        }
        List<MlccFabricInfo> fabricInfos = fabricInfoMapper.selectList(wrapper);
        // 判断面料对应的面料组是否存在，如果不存在，则不显示这个面料
        Iterator<MlccFabricInfo> iterator = fabricInfos.iterator();
        while (iterator.hasNext()) {
            MlccFabricInfo next = iterator.next();
            if (next.getGroupId() != null) {
                QueryWrapper<MlccGroupInfo> groupInfoQueryWrapper = new QueryWrapper<>();
                groupInfoQueryWrapper.eq("status", 0).eq("id", next.getGroupId());
                MlccGroupInfo groupInfo = groupInfoMapper.selectOne(groupInfoQueryWrapper);
                if (groupInfo == null) {
                    iterator.remove();
                }
            }
        }
        return fabricInfos;
    }


    /**
     * 未支付个定订单详情
     *
     * @param token
     * @param orderID
     */
    @Override
    public MlccSingleOrderInfo getSingleDetail(String token, String orderSn) {
        if (!fabricUtil.checkToken(token)) return null;
        return fabricUtil.getSingleOrderDetailById3(orderSn);
    }

    /**
     * 获取未支付订单详情页面的品牌表
     *
     * @param token
     */
    @Override
    public List<String> getTitle(String token) {
        if (!fabricUtil.checkToken(token)) return null;
        MlccUserInfo userDetail = fabricUtil.getUserDetail(token);
        return Arrays.asList(userDetail.getBrandLabels().split(","));
    }

    /**
     * 提交订单
     *
     * @param token        令牌
     * @param orderID      订单ID
     * @param remark       备注
     * @param shiyang      式样
     * @param modifiedYang 改款打样
     * @param emergency    紧急状况
     * @param brandLabel   品牌标
     * @param orderMoney   订单金额
     */
    @Override
    public int submitOrder(String token, int orderID, String remark, String shiyang, String modifiedYang, String emergency, String orderMoney, String brandLabel) {
        // 验证token
        if (!fabricUtil.checkToken(token)) return -1;

        MlccUserInfo userDetail = fabricUtil.getUserDetail(token);
        /*MlccSingleOrderInfo info = singleOrderInfoMapper.selectById(orderID);*/
        QueryWrapper<MlccSingleOrderInfo> singleOrderInfoQueryWrapper = new QueryWrapper<>();
        singleOrderInfoQueryWrapper.eq("id", orderID).eq("status", 0);
        MlccSingleOrderInfo info = singleOrderInfoMapper.selectOne(singleOrderInfoQueryWrapper);
        if (info == null) {
            System.out.println("提交的订单不存在");
            return 0;
        }

        // 改变订单状态，把草稿订单改为未支付的订单
        info.setRemark(remark).setShiyang(shiyang).setModifiedYang(modifiedYang)
                .setEmergency(emergency).setOrderMoney(orderMoney).setCreateTime(new Date())
                .setUpdateBy(userDetail.getUsername()).setStatus(11).setBrandLabel(brandLabel);

        int insert = singleOrderInfoMapper.updateById(info);
        if (insert > 0) {
            // 1、往订单流水表添加数据（添加之前判断之前是否有数据）必须确保一条订单只有一条流水记录
            QueryWrapper<MlccBusinessWaterInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("order_sn", info.getOrderSn());
            List<MlccBusinessWaterInfo> waterList = waterInfoMapper.selectList(wrapper);
            if (waterList == null || waterList.size() == 0) {
                MlccBusinessWaterInfo wrater = new MlccBusinessWaterInfo();
                wrater.setOrderId(info.getId() + "").setType(1).setUserId(userDetail.getId() + "")
                        .setCostMoney(info.getOrderMoney()).setYewuInstructions("正常订单，前端个订提交订单")
                        .setYewuDeatil("提交订单").setStatus(0).setRemark("个订下单提交订单，草稿订单变为个订订单")
                        .setSysOrgCode(userDetail.getOrgCode())
                        .setCreateBy(userDetail.getUsername()).setUpdateBy(userDetail.getUsername())
                        .setOrderSn(info.getOrderSn()).setStoreId(info.getStoreId()).setId(UUID.randomUUID().toString().substring(0, 15));
                waterInfoMapper.insert(wrater);
            }

            // 2、往订单跟踪表添加一条记录
            MlccTrackingOrder trackingOrder = new MlccTrackingOrder();
            trackingOrder.setId(UUID.randomUUID().toString().substring(0, 15)).setOrderSn(info.getOrderSn())
                    .setThing("提交订单")
                    .setOrderType(1).setRemark("前端提交了个订订单").setCreateBy(userDetail.getUsername())
                    .setUpdateBy(userDetail.getUsername());
            trackingOrderMapper.insert(trackingOrder);
            return 1;
        } else {
            return 0;
        }
    }

    /**
     * 根据绣字类型查询绣字高度列表
     *
     * @param xiuzitype
     */
    @Override
    public List<MlccEmbdtypePrice> getXiuziList(String xiuzitype) {
        QueryWrapper<MlccEmbdtypePrice> wrapper = new QueryWrapper<>();
        wrapper.eq("embroidered_type", xiuzitype);
        return embdtypePriceMapper.selectList(wrapper);
    }

    /**
     * 查询绣字位置集合
     *
     * @param categoryID 类别ID
     */
    @Override
    public List<MlccCategoryLocaltion> listXiuziHandler(String categoryID) {
        QueryWrapper<MlccCategoryLocaltion> wrapper = new QueryWrapper<>();
        wrapper.eq("category_id", categoryID);
        return locatiomMapper.selectList(wrapper);
    }

    /**
     * 个订界面获取类别和工艺数据
     *
     * @param mouldid
     * @param typeids
     */
    @Override
    public List<MlccModuleSmallTemplate> getTypeAndProcess(String token, String mouldid, String typeids) {
        if (!fabricUtil.checkToken(token)) return null;
        List<String> typeidslist = Arrays.asList(typeids.split(","));
        // 经过过滤之后的查询条件
        ArrayList<Integer> lastCateid = new ArrayList<>();
        // 这些category_id必须是is_type为3的数据，所以需要过滤
        for (String cateid : typeidslist) {
            MlccCategoryInfo categoryInfo = categoryInfoMapper.selectById(cateid);
            if (categoryInfo != null && categoryInfo.getIsType() == 3) {
                lastCateid.add(categoryInfo.getId());
            }

        }

        QueryWrapper<MlccModuleSmallTemplate> wrapper = new QueryWrapper<>();
        if (lastCateid.size() > 0) {
            wrapper.in("category_id", lastCateid);
        } else {
            wrapper.eq("category_id", -1);
        }
        wrapper.eq("module_id", mouldid).eq("istype", 0).orderByAsc("numbers");
        List<MlccModuleSmallTemplate> smallTemplateList = moduleSmallTemplateMapper.selectList(wrapper);
        if (smallTemplateList != null && smallTemplateList.size() > 0) {
            for (MlccModuleSmallTemplate template : smallTemplateList) {
                QueryWrapper<MlccCategoryInfo> wrapper1 = new QueryWrapper<>();
                wrapper1.eq("parent_id", template.getId()).eq("status", 0).orderByAsc("numbers");
                List<MlccCategoryInfo> categoryInfos = categoryInfoMapper.selectList(wrapper1);
                // 是否存在互斥项？
                if (categoryInfos != null && categoryInfos.size() > 0) {
                    for (MlccCategoryInfo categoryInfo : categoryInfos) {
                        QueryWrapper<MlccMutexInfo> wrapper2 = new QueryWrapper<>();
                        wrapper2.eq("category_id", categoryInfo.getId());
                        List<MlccMutexInfo> mutexInfos = mutexInfoMapper.selectList(wrapper2);
                        if (mutexInfos != null && mutexInfos.size() > 0) {
                            for (MlccMutexInfo mutexInfo : mutexInfos) {
                                // 如果存在互斥，给互斥的选项标记互斥
                                if (mutexInfo != null) {
                                    String[] split = mutexInfo.getCategoryOther().split(",");
                                    for (String s : split) {
                                        for (MlccCategoryInfo info : categoryInfos) {
                                            if (s.equals(info.getId())) {
                                                info.setNot(1);
                                                System.out.println(info);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                template.setCategoryInfoList(categoryInfos);
            }
        }
        return smallTemplateList;
    }

    /**
     * 获取驳宽和珠边宽度
     *
     * @param token
     * @param mouldid
     * @return
     */
    @Override
    public List<MlccModuleSmallTemplate> getBokuan(String token, int mouldid) {
        if (!fabricUtil.checkToken(token)) return null;
        QueryWrapper<MlccModuleSmallTemplate> wrapper = new QueryWrapper<>();
        wrapper.eq("module_id", mouldid).in("istype", Arrays.asList(1, 2)).orderByAsc("numbers");
        List<MlccModuleSmallTemplate> smallTemplateList = moduleSmallTemplateMapper.selectList(wrapper);
        for (MlccModuleSmallTemplate template : smallTemplateList) {
            QueryWrapper<MlccCategoryInfo> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("parent_id", template.getId());
            template.setCategoryInfoList(categoryInfoMapper.selectList(wrapper1));
        }
        return smallTemplateList;
    }

    /**
     * 个订模板获取详情
     *
     * @param token
     * @param orderSn
     * @return
     */
    @Override
    public MlccSignModuleInfo getmoduleDetail(String token, String orderSn) {
        if (!fabricUtil.checkToken(token)) return null;
//        return fabricUtil.getModuleDetail2(orderSn);
        return fabricUtil.getSingleMoudleDetailById3(orderSn);
    }

    /**
     * 继续填写个订订单
     *
     * @param token   令牌
     * @param orderSn 个订订单编号
     * @return
     */
    @Override
    public MlccSingleOrderInfo continueSingleOrder(String token, String orderSn) {
        if (!fabricUtil.checkToken(token)) return null;
        return fabricUtil.getSingleOrderDetailById3(orderSn);
    }

    /**
     * 用户详情
     *
     * @param token
     * @return
     */
    @Override
    public MlccUserInfo getUserDetail(String token) {
        if (!fabricUtil.checkToken(token)) return null;
        MlccUserInfo userDetail = fabricUtil.getUserDetail(token);
        // 查询公司信息
        QueryWrapper<MlccCompanyInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("company_code", userDetail.getCompanyOrgcode());
        MlccCompanyInfo companyInfo = companyInfoMapper.selectOne(wrapper);
        // 根据公司数据找到公司账号
        MlccUserInfo companyUser = userInfoMapper.selectById(companyInfo.getUserId());
        if (companyUser == null) {
            throw new RuntimeException("公司账号不存在");
        }
        return companyUser;
    }

    /**
     * 个定预览订单显示加价服务
     *
     * @param orderSn 订单编号
     */
    @Override
    public JSONObject listJiajia(String orderSn) {
        JSONObject jsonObject = new JSONObject();
        BigDecimal allMoney = new BigDecimal(0); // 存放最终的加价金额
        List<MlccPriceSystemCostRecord> result = new ArrayList<>(); // 存放所有的加价列表
        // 查询个订订单下的所有产品
        QueryWrapper<MlccProductInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn);
        List<MlccProductInfo> productInfoList = productInfoMapper.selectList(wrapper);
        if (productInfoList != null && productInfoList.size() > 0) {
            for (MlccProductInfo productInfo : productInfoList) {
                if (productInfo != null) {
                    // 1、获取这个产品的品类
                    String PLID = fabricUtil.getpingleiFromProduct(productInfo);
                    System.out.println("品类ID是多少》》》》》" + PLID);
                    // 2、查询产品名下的定制项参数
                    List<String> dzxList = fabricUtil.getDDZXFromProduct(productInfo);
                    // 定制项的编号集合
                    List<String> dzxcodes = fabricUtil.dzxCode(dzxList);
                    // 根据品类和业务类型确定价格体系
                    QueryWrapper<MlccPriceSystemPinglei> wrapper1 = new QueryWrapper<>();
                    wrapper1.eq("category_id", PLID).eq("business_type", 0).eq("is_gongyi", 0);
                    MlccPriceSystemPinglei systemPinglei = priceSystemPingleiMapper.selectOne(wrapper1);
                    if (systemPinglei != null) {
                        // 1、查询产品定制下的参数的价格
                        if (dzxList != null && dzxList.size() > 0) {
                            QueryWrapper<MlccPriceSystemCostRecord> wrapper2 = new QueryWrapper<>();
                            wrapper2.eq("price_system_id", systemPinglei.getId()).eq("cost_item", PLID).in("cost_code", dzxcodes)
                                    .eq("type", 1);
                            List<MlccPriceSystemCostRecord> dsxrecords = recordMapper.selectList(wrapper2);
                            if (dsxrecords != null && dsxrecords.size() > 0) {
                                for (MlccPriceSystemCostRecord dsxrecord : dsxrecords) {
                                    dsxrecord.setProductName(productInfo.getProductName());
                                    allMoney = allMoney.add(dsxrecord.getPrice());
                                    result.add(dsxrecord);
                                }
                            }
                        }

                        // 2、查询这个产品撞色的加价
                        String zhuangseIds = productInfo.getZhuangseIds();
                        if (zhuangseIds != null && !"".equals(zhuangseIds)) {
                            String[] split = zhuangseIds.split(",");
                            if (split != null && split.length > 0) {
                                for (String idAandColor : split) {
                                    // 拿到每个撞色ID
                                    String[] array = idAandColor.split("/");
                                    QueryWrapper<MlccPriceSystemCostRecord> wrapper2 = new QueryWrapper<>();
                                    MlccContrastcolorInfo contrastcolorInfo = contrastColorMapper.selectById(array[0]);
                                    wrapper2.eq("price_system_id", systemPinglei.getId()).eq("cost_item", PLID)
                                            .eq("type", 3);
                                    if (contrastcolorInfo != null) {
                                        wrapper2.eq("cost_code", contrastcolorInfo.getCode());
                                    }
                                    MlccPriceSystemCostRecord colorRecord = recordMapper.selectOne(wrapper2);
                                    if (colorRecord != null) {
                                        colorRecord.setProductName(productInfo.getProductName());
                                        allMoney = allMoney.add(colorRecord.getPrice());
                                        result.add(colorRecord);
                                    }
                                }
                            }
                        }

                        // 3、查询绣字类型
                        String xiuziWeizhi = productInfo.getXiuziType();
                        System.out.println("价格ID是多少》》》" + systemPinglei.getId());
                        if (xiuziWeizhi != null && !"".equals(xiuziWeizhi) && !"无绣字".equals(xiuziWeizhi)) {
                            QueryWrapper<MlccPriceSystemCostRecord> wrapper2 = new QueryWrapper<>();
                            wrapper2.eq("price_system_id", systemPinglei.getId()).eq("cost_item", PLID).eq("type", 2).eq("cost_name", xiuziWeizhi);
                            MlccPriceSystemCostRecord fontLocationRecord = recordMapper.selectOne(wrapper2);
                            if (fontLocationRecord != null) {
                                fontLocationRecord.setProductName(productInfo.getProductName());
                                allMoney = allMoney.add(fontLocationRecord.getPrice());
                                result.add(fontLocationRecord);
                            } else {
                                QueryWrapper<MlccPriceSystemCostRecord> wrapper3 = new QueryWrapper<>();
                                wrapper3.eq("price_system_id", systemPinglei.getId()).eq("cost_item", PLID).eq("type", 2).eq("cost_name", "绣字工艺");
                                MlccPriceSystemCostRecord fontLocationRecord2 = recordMapper.selectOne(wrapper3);
                                if (fontLocationRecord2 != null) {
                                    fontLocationRecord.setProductName(productInfo.getProductName());
                                    allMoney = allMoney.add(fontLocationRecord.getPrice());
                                    result.add(fontLocationRecord);
                                }
                            }
                        }
                    }
                }
            }
        }
        System.out.println("所有的数据" + result);
        jsonObject.put("code", 0);
        jsonObject.put("data", result);
        jsonObject.put("allMoney", allMoney.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
        return jsonObject;
    }

    /**
     * 计算订单价格
     *
     * @param orderPrice   除了加价之外的订单金额
     * @param shiyang      式样（加价服务）
     * @param modifiedYang 改款打样（加价服务）
     * @param emergency    紧急指数（加价服务）
     */
    @Override
    public String compudePrice(Double orderPrice, String shiyang, String modifiedYang, String emergency) {
        BigDecimal price = new BigDecimal(orderPrice);
        // 12 订单的附加条件需要额外算钱
        // 12.1 计算式样的加价
        if (shiyang != null && !"".equals(shiyang)) {
            QueryWrapper<MlccPriceSystemCostRecord> recoredWrapper = new QueryWrapper<>();
            recoredWrapper.eq("cost_name", shiyang);
            MlccPriceSystemCostRecord ShiyangRecord = recordMapper.selectOne(recoredWrapper);
            if (ShiyangRecord != null) {
                price = price.add(ShiyangRecord.getPrice());
            }
        }

        // 12.2 计算该款打样的加价
        if (modifiedYang != null && !"".equals(modifiedYang)) {
            QueryWrapper<MlccPriceSystemCostRecord> recoredWrapper = new QueryWrapper<>();
            recoredWrapper.eq("cost_name", modifiedYang);
            MlccPriceSystemCostRecord ShiyangRecord = recordMapper.selectOne(recoredWrapper);
            if (ShiyangRecord != null) {
//                orderPrice += (ShiyangRecord.getPrice().doubleValue());
                price = price.add(ShiyangRecord.getPrice());
            }
        }

        // 12.3 计算紧急指数的加价
        if (emergency != null && !"".equals(emergency)) {
            QueryWrapper<MlccPriceSystemCostRecord> recoredWrapper = new QueryWrapper<>();
            recoredWrapper.eq("cost_name", emergency);
            MlccPriceSystemCostRecord ShiyangRecord = recordMapper.selectOne(recoredWrapper);
            if (ShiyangRecord != null) {
//                orderPrice += (ShiyangRecord.getPrice().doubleValue());
                price = price.add(ShiyangRecord.getPrice());
            }
        }
        return price.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() + "";
    }

    /**
     * 获取面料列表
     *
     * @param page       分页器
     * @param fabricCode 面料编码
     */
    @Override
    public IPage<MlccFabricInfo> getFabricListnew(Page<MlccFabricInfo> page, String fabricCode, Integer type) {
        QueryWrapper<MlccFabricInfo> wrapper = new QueryWrapper<>();
        if (fabricCode != null && !"".equals(fabricCode)) {
            wrapper.like("fabric_code", fabricCode);
        }
        if (type != null) {
            wrapper.eq("fabric_type_id", type);
        }
        wrapper.eq("status", 0).orderByAsc("paixu");
        IPage<MlccFabricInfo> infoIPage = fabricInfoMapper.selectPage(page, wrapper);
        List<MlccFabricInfo> records = infoIPage.getRecords();
        if (records != null && records.size() > 0) {
            // 判断面料对应的面料组是否存在，如果不存在，则不显示这个面料
            Iterator<MlccFabricInfo> iterator = records.iterator();
            while (iterator.hasNext()) {
                MlccFabricInfo next = iterator.next();
                if (next.getGroupId() != null) {
                    QueryWrapper<MlccGroupInfo> groupInfoQueryWrapper = new QueryWrapper<>();
                    groupInfoQueryWrapper.eq("status", 0).eq("id", next.getGroupId());
                    MlccGroupInfo groupInfo = groupInfoMapper.selectOne(groupInfoQueryWrapper);
                    if (groupInfo == null) {
                        iterator.remove();
                    }
                }
            }
        }
        return infoIPage;
    }

    /**
     * 保存或更新附加条件
     *
     * @param productid 产品id
     * @param priceid   成本价格ID
     * @param type      上级id
     */
    @Override
    public int saveFujia(String productid, String priceid, String type) {
        if (priceid == null || type == null || "".equals(priceid) || "".equals(type)) {
            return 0;
        }
        boolean flag = false; // 用来判定不同是否需要追加
        String newid = type.trim() + "/" + priceid.trim(); // 新的组合
        MlccProductInfo productInfo = productInfoMapper.selectById(productid);
        if (productInfo != null) {
            String fujiaids = productInfo.getFujiaids();
            if (fujiaids != null && !"".equals(fujiaids)) {
                List<String> strings = Arrays.asList(fujiaids.split(","));
                ArrayList<String> lastList = new ArrayList<>(strings);
                // 判断上级id是否重复，重复的话替换掉老的数据
                for (int i = 0; i < lastList.size(); i++) {
                    String[] split = lastList.get(i).split("/");
                    if (type.equals(split[0])) {
                        // 重复了,去除原来的，加上最新的
                        lastList.remove(i);
                        lastList.add(newid.trim());
                        flag = false; // 不需要最佳，只需要替换
                    } else {
                        flag = true; // 需要追加
                    }
                }
                if (flag) {
                    lastList.add(newid.trim());
                }
                String strip = StringUtils.strip(lastList.toString(), "[  ]");
                String replace = strip.replace(" ", "");
                productInfo.setFujiaids(replace);
            } else {
                // 说明是空的
                productInfo.setFujiaids(newid.trim());
            }
        }
        return productInfoMapper.updateById(productInfo);
    }

    /**
     * 真·计算个订订单价格
     *
     * @param price   还没有加上附加条件的金额
     * @param orderSn 订单编号
     */
    @Override
    public double getallPrice(double price, String orderSn) {
        BigDecimal last = new BigDecimal(price);
        QueryWrapper<MlccProductInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn);
        List<MlccProductInfo> productInfos = productInfoMapper.selectList(wrapper);
        if (productInfos != null && productInfos.size() > 0) {
            for (MlccProductInfo info : productInfos) {

                if (info.getFujiaids() != null && !"".equals(info.getFujiaids())) {
                    String[] split = info.getFujiaids().split(",");
                    for (String priceid : split) {
                        String[] split1 = priceid.split("/");
                        MlccPriceSystemCostRecord record = recordMapper.selectById(split1[1]);
                        last = last.add(record.getPrice());
                    }
                }

                /*// 查询式样的价格
                if (info.getShiyang() != null && !"".equals(info.getShiyang())) {
                    MlccPriceSystemCostRecord record = recordMapper.selectById(info.getShiyang());
                    last += record.getPrice().doubleValue();
                }
                // 查询紧急指数的价格
                if (info.getEmergency() != null && !"".equals(info.getEmergency())) {
                    MlccPriceSystemCostRecord record = recordMapper.selectById(info.getEmergency());
                    last += record.getPrice().doubleValue();
                }
                // 查询该款打样的价格
                if (info.getModifiedYang() != null && !"".equals(info.getModifiedYang())) {
                    MlccPriceSystemCostRecord record = recordMapper.selectById(info.getModifiedYang());
                    last += record.getPrice().doubleValue();
                }*/
            }
        }
        return last.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    /**
     * 获取个订定单的收费服务项（里布、低领尼、纽扣）
     *
     * @param orderSn 个订订单编号
     */
    @Override
    public JSONObject shouFeifuwuXiang(String orderSn) {
        JSONObject result = new JSONObject();
        ArrayList<FuwujiaEntity> list = new ArrayList<>();
        BigDecimal allprice = new BigDecimal(0);
        QueryWrapper<MlccProductInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn);
        List<MlccProductInfo> productInfos = productInfoMapper.selectList(wrapper);
        if (productInfos != null && productInfos.size() > 0) {
            for (MlccProductInfo productInfo : productInfos) {
                // 获取品类信息
                String plid = fabricUtil.getpingleiFromProduct(productInfo);
                MlccCategoryInfo categoryInfo = categoryInfoMapper.selectById(plid);
                // 计算里布的价格
                if (productInfo.getLibuId() != null) {
                    MlccMaterialLibuInfo libuInfo = libuInfoMapper.selectById(productInfo.getLibuId());
                    if (libuInfo != null && libuInfo.getSalesPrice() != null) {
                        if (libuInfo.getSalesPrice().doubleValue() != 0) {
                            FuwujiaEntity entity = new FuwujiaEntity();
                            entity.setPlname(categoryInfo.getCategoryName()).setName(libuInfo.getLibuCode())
                                    .setProductName(productInfo.getProductName())
                                    .setPrice(libuInfo.getSalesPrice()).setType("里布");
                            allprice = allprice.add(libuInfo.getSalesPrice());
                            list.add(entity);
                        }
                    }
                }

                // 计算低领尼的价格
                if (productInfo.getDilinliId() != null) {
                    MlccDilinniInfo dilinniInfo = dilinniInfoMapper.selectById(productInfo.getDilinliId());
                    if (dilinniInfo != null && dilinniInfo.getSalesPrice() != null) {
                        if (dilinniInfo.getSalesPrice().doubleValue() != 0) {
                            FuwujiaEntity entity = new FuwujiaEntity();
                            entity.setPlname(categoryInfo.getCategoryName()).setName(dilinniInfo.getDilinniNumber())
                                    .setProductName(productInfo.getProductName())
                                    .setPrice(dilinniInfo.getSalesPrice()).setType("底领呢");
                            allprice = allprice.add(dilinniInfo.getSalesPrice());
                            list.add(entity);
                        }
                    }
                }

                // 计算纽扣的钱
                if (productInfo.getButtonsIds() != null) {
                    MlccButtonsInfo buttonsInfo = buttonsInfoMapper.selectById(productInfo.getButtonsIds());
                    if (buttonsInfo != null && buttonsInfo.getRetailPrice() != null) {
                        if (buttonsInfo.getRetailPrice().doubleValue() != 0) {
                            FuwujiaEntity entity = new FuwujiaEntity();
                            entity.setPlname(categoryInfo.getCategoryName()).setName(buttonsInfo.getButtonsName())
                                    .setProductName(productInfo.getProductName())
                                    .setPrice(buttonsInfo.getRetailPrice()).setType("纽扣");
                            allprice = allprice.add(buttonsInfo.getRetailPrice());
                            list.add(entity);
                        }
                    }
                }
            }
        }
        result.put("code", 0);
        result.put("data", list);
        result.put("price", allprice.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
        return result;
    }

    /**
     * 获取个订下的产品列表
     *
     * @param orderSn 订单编号
     */
    @Override
    public List<MlccProductInfo> productList(String orderSn) {
        QueryWrapper<MlccProductInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn);
        List<MlccProductInfo> productInfos = productInfoMapper.selectList(wrapper);
        if (productInfos != null && productInfos.size() > 0) {
            for (MlccProductInfo info : productInfos) {
                String plid = fabricUtil.getpingleiFromProduct(info);
                MlccCategoryInfo categoryInfo = categoryInfoMapper.selectById(plid);
                if (categoryInfo != null) {
                    info.setPingleiName(categoryInfo.getCategoryName());
                }
                if (info.getGysId() != null) {
                    MySysUser sysUser = sysUserMapper.selectById(info.getGysId());
                    if (sysUser != null) {
                        info.setGysName(sysUser.getRealname());
                    }
                }
            }
        }
        return productInfos;
    }

    /**
     * 获取个订下的产品列表(用于个订产品发货)
     *
     * @param orderSn 订单编号
     */
    @Override
    public List<MlccProductInfo> productListfa(String orderSn) {
        QueryWrapper<MlccProductInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn).eq("is_out", 0);
        List<MlccProductInfo> productInfos = productInfoMapper.selectList(wrapper);
        if (productInfos != null && productInfos.size() > 0) {
            for (MlccProductInfo info : productInfos) {
                String plid = fabricUtil.getpingleiFromProduct(info);
                MlccCategoryInfo categoryInfo = categoryInfoMapper.selectById(plid);
                if (categoryInfo != null) {
                    info.setPingleiName(categoryInfo.getCategoryName());
                }
                if (info.getGysId() != null) {
                    MySysUser sysUser = sysUserMapper.selectById(info.getGysId());
                    if (sysUser != null) {
                        info.setGysName(sysUser.getRealname());
                    }
                }
            }
        }
        return productInfos;
    }

    /**
     * 个订查询附加条件列表
     *
     * @param orderSn 个订订单编号
     */
    @Override
    public List<MlccPriceSystemCostRecord> listFujia(String orderSn) {
        // 存放最终结果
        ArrayList<MlccPriceSystemCostRecord> records = new ArrayList<>();
        QueryWrapper<MlccProductInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn);
        List<MlccProductInfo> productInfos = productInfoMapper.selectList(wrapper);
        if (productInfos != null && productInfos.size() > 0) {
            for (MlccProductInfo info : productInfos) {
                // 获取产品品类id
                String plid = fabricUtil.getpingleiFromProduct(info);
                MlccCategoryInfo categoryInfo = categoryInfoMapper.selectById(plid);
                if (info.getFujiaids() != null) {
                    String fujiaids = info.getFujiaids();
                    String[] split = fujiaids.split(",");// 格式：上级id/成本项id
                    if (split != null && split.length > 0) {
                        for (String topandid : split) {
                            String[] split1 = topandid.split("/");
                            MlccPriceSystemCostRecord record = recordMapper.selectById(split1[1]);
                            if (record != null) {
                                record.setProductName(info.getProductName()).setCateogryName(categoryInfo.getCategoryName());
                                records.add(record);
                            }
                        }
                    }
                }
            }
        }
        return records;
    }

    /**
     * 个订产品查询附加条件列表————用于个订加工厂展示
     *
     * @param productid 产品id
     */
    @Override
    public List<MlccPriceSystemCostRecord> listFujiaByProduct(String productid) {
        // 存放最终结果
        ArrayList<MlccPriceSystemCostRecord> records = new ArrayList<>();
        MlccProductInfo info = productInfoMapper.selectById(productid);
        if (info != null) {
            // 获取产品品类id
            String plid = fabricUtil.getpingleiFromProduct(info);
            MlccCategoryInfo categoryInfo = categoryInfoMapper.selectById(plid);
            if (info.getFujiaids() != null) {
                String fujiaids = info.getFujiaids();
                String[] split = fujiaids.split(",");// 格式：上级id/成本项id
                if (split != null && split.length > 0) {
                    for (String topandid : split) {
                        String[] split1 = topandid.split("/");
                        MlccPriceSystemCostRecord record = recordMapper.selectById(split1[1]);
                        if (record != null) {
                            record.setProductName(info.getProductName()).setCateogryName(categoryInfo.getCategoryName());
                            records.add(record);
                        }
                    }
                }
            }
        }
        return records;
    }

    /**
     * 个订订单导出产品
     *
     * @param orderSn  订单编号
     * @param response 响应对象
     */
    @Override
    public void dingleExcel(String orderSn, HttpServletResponse response) throws Exception {
        QueryWrapper<MlccSingleOrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn);
        // 拿到订单的基本信息
        MlccSingleOrderInfo one = singleOrderInfoMapper.selectOne(wrapper);
        // 拿到订单下的每个产品
        QueryWrapper<MlccProductInfo> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("order_sn", orderSn);
        List<MlccProductInfo> productInfoList = productInfoMapper.selectList(wrapper1);
        if (productInfoList != null && productInfoList.size() > 0) {
            for (MlccProductInfo info : productInfoList) {
                // 查询定制项的信息
                Map<String, String> categoryMap = getCategoryFromProduct(info);
                // 获取净体尺寸名称
                List<String> stringList = getSizeNameFromProduct(info);
                // 获取净体尺寸键值对
                Map<String, String> jingSizeNameAndValue = getSizeNameAndValueFromProduct(info, 1);
                // 获取成衣尺寸键值对
                Map<String, String> chengyiSizeNameAandValue = getSizeNameAndValueFromProduct(info, 0);
                info.setCategoryMap(categoryMap).setStringList(stringList)
                        .setJingSizeNameAndValue(jingSizeNameAndValue).setChengyiSizeNameAandValue(chengyiSizeNameAandValue);
            }
        }
        // 导出excel
        exportExcel(productInfoList, response);
    }

    /**
     * 新·个订产品状态更新，获取产品状态
     *
     * @param proid 产品id
     */
    @Override
    public List<MlccDataType> listProductStatus(String proid) {
        MlccProductInfo info = productInfoMapper.selectById(proid);
        String s = fabricUtil.getpingleiFromProduct(info);
        // 根据品类id获取产品的状态参数
        QueryWrapper<MlccDataType> wrapper = new QueryWrapper<>();
        wrapper.eq("category_id", s);
        return dataTypeMapper.selectList(wrapper);
    }

    /**
     * 根据产品的id获取产品的所有类别
     *
     * @param product 产品对象
     */
    public Map<String, String> getCategoryFromProduct(MlccProductInfo product) {
        HashMap<String, String> result = new HashMap<>();
        String categoryIds = product.getCategoryIds();
        if (categoryIds != null && !"".equals(categoryIds)) {
            String[] categoryArray = categoryIds.split(",");
            for (String categoryid : categoryArray) {
                MlccCategoryInfo info = categoryInfoMapper.selectById(categoryid);
                if (info != null && info.getIsType() == 0) {
                    MlccModuleSmallTemplate template = moduleSmallTemplateMapper.selectById(info.getParentId());
                    if (template != null) {
                        result.put(template.getParameter(), info.getCategoryName());
                    }
                }
            }
        }
        return result;
    }

    /**
     * 根据产品获取对应的净体尺寸名称
     *
     * @param product 产品对象
     */
    public List<String> getSizeNameFromProduct(MlccProductInfo product) {
        ArrayList<String> list = new ArrayList<>();
        String plid = fabricUtil.getpingleiFromProduct(product);
        System.out.println("这个产品的平类id是++++++" + plid);
        QueryWrapper<MlccBodySizeInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("category_id", plid).eq("is_jin", 1);
        List<MlccBodySizeInfo> sizeInfos = bodySizeMapper.selectList(wrapper);
        if (sizeInfos != null && sizeInfos.size() > 0) {
            for (MlccBodySizeInfo sizeInfo : sizeInfos) {
                list.add(sizeInfo.getBodySizename());
            }
        }
        return list;
    }

    /**
     * 根据产品获取对应的净体尺寸或成衣尺寸键值对
     *
     * @param product 产品对象
     * @param type    0 成衣尺寸 1净体尺寸
     */
    public Map<String, String> getSizeNameAndValueFromProduct(MlccProductInfo product, Integer type) {
        HashMap<String, String> map = new HashMap<>();
        String oldbodySizeIds = product.getOldbodySizeIds();
        if (oldbodySizeIds != null && !"".equals(oldbodySizeIds)) {
            String[] sizeIdAndValue = oldbodySizeIds.split(",");
            for (String one : sizeIdAndValue) {
                String[] split = one.split("/");
                MlccBodySizeInfo bodySizeInfo = bodySizeMapper.selectById(split[0]);
                if (type == 1) {
                    if (bodySizeInfo.getIsJin() == 1) {
                        map.put(bodySizeInfo.getBodySizename(), split[1]);
                    }
                } else if (type == 0) {
                    if (bodySizeInfo.getIsJin() == 0) {
                        map.put(bodySizeInfo.getBodySizename(), split[1]);
                    }
                }
            }
        }
        return map;
    }

    /**
     * 根据产品对象获取面料编号
     *
     * @param product 产品对象
     */
    public String getfabricCode(MlccProductInfo product) {
        String fabricIds = product.getFabricIds();
        if (fabricIds != null && !"".equals(fabricIds)) {
            String[] idAandMishu = fabricIds.split("/");
            if (idAandMishu != null) {
                MlccFabricInfo fabricInfo = fabricInfoMapper.selectById(idAandMishu[0]);
                if (fabricInfo != null) {
                    return fabricInfo.getFabricCode();
                }
            }
        }
        return "";
    }

    /**
     * 导出个订Excel
     *
     * @param list     产品列表
     * @param response 响应对象
     * @throws Exception
     */
    public void exportExcel(List<MlccProductInfo> list, HttpServletResponse response) throws Exception {
        ServletOutputStream out = response.getOutputStream();
        // 接下来开始导出excel
        try {
            MyExcelUtils eeu = new MyExcelUtils();
            HSSFWorkbook workbook = new HSSFWorkbook();
            // 遍历产品
            int j = 0;
            for (MlccProductInfo info : list) {
                List<String> baseTitle = MyExcelUtils.baseTitleSingle();
                baseTitle.addAll(info.getStringList());
                // 单个sheet的数据
                List<List<String>> productdata = new ArrayList<List<String>>();
                // 存放行的数据
                ArrayList<String> rowData = new ArrayList<>();
                // 设置基本数据
                // 找到客户姓名
                QueryWrapper<MlccSingleOrderInfo> wrapper = new QueryWrapper<>();
                wrapper.eq("order_sn", info.getOrderSn());
                MlccSingleOrderInfo singleOrderInfo = singleOrderInfoMapper.selectOne(wrapper);
                rowData.add(singleOrderInfo.getCustomerName());
                rowData.add(info.getSex() == 1 ? "男" : "女");
                rowData.add(getfabricCode(info));
                rowData.add(info.getNumbers() + fabricUtil.getplNameFromProduct(info));
                // 设置款式
                StringBuffer kuanshi = new StringBuffer();
                Map<String, String> map = info.getCategoryMap();
                Set<String> keySet = map.keySet();
                for (String key : keySet) {
                    String value = map.get(key);
                    kuanshi.append(key + ": " + value + "\n");
                }
                rowData.add(kuanshi.toString());
                // 设置成衣尺寸
                StringBuffer chengyiSize = new StringBuffer();
                Map<String, String> chengyiSizeNameAandValue = info.getChengyiSizeNameAandValue();
                Set<String> keySet1 = chengyiSizeNameAandValue.keySet();
                for (String key : keySet1) {
                    String value = chengyiSizeNameAandValue.get(key);
                    chengyiSize.append(key + "：" + value + "\n\t");
                }
                rowData.add(chengyiSize.toString());
                rowData.add(info.getLiangtiRemark());

                // 基础数据设置完成 下面开始设置净体尺寸的数据
                Map<String, String> jingSizeNameAndValue = info.getJingSizeNameAndValue();
                for (int k = 0; k < baseTitle.size(); k++) {
                    if (k >= 7 && k < baseTitle.size()) {
                        if (jingSizeNameAndValue != null) {
                            Set<String> keySet2 = jingSizeNameAndValue.keySet();
                            for (String key : keySet2) {
                                String value = jingSizeNameAndValue.get(key);
                                // 如果标题和尺码的名称一致
                                if (baseTitle.get(k).equals(key)) {
                                    rowData.add(value);
                                }
                            }
                        }
                    }
                }
                productdata.add(rowData); // 数据就绪完毕
                // 遍历终止
                String[] objects = baseTitle.toArray(new String[baseTitle.size()]);
                eeu.exportExcel(workbook, j, info.getProductName(), objects, productdata, out);
                j++;
            }
            //将所有的数据一起写入，然后再关闭输入流。
            workbook.write(out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
            out.close();
        }
    }
}
